package edu.utexas.mapreduce;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Implementation of the InputStream interface that provides
 * lazy initialization for an URL connection.  The connection 
 * to the URL will be opened on access to any of the InputStream
 * methods.
 */
public class URLInputStream extends InputStream {

	private URL url;
	private InputStream inputStream;
	
	URLInputStream(URL url) {
		this.url = url;
		this.inputStream = null;
	}
	
	private InputStream getInputStream() throws IOException {
		if (inputStream == null) {
			inputStream = url.openStream();
		}	
		return inputStream;
	}
	
	//
	// forward all InputStream methods to the internal URL InputStream
	//
	
	@Override
	public int read() throws IOException {
		return getInputStream().read();
	}
	
	@Override
	public int read(byte[] b) throws IOException {
		return getInputStream().read(b);
	}
	
	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		return getInputStream().read(b, off, len);
	}
	
	@Override
	public long skip(long n) throws IOException {
		return getInputStream().skip(n);
	}

    @Override
    public int available() throws IOException {
		return getInputStream().available();
	}
    
    @Override
    public void close() throws IOException {
		getInputStream().close();
	}
    
    @Override
    public void mark(int readlimit) {
		try {
			getInputStream().mark(readlimit);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void reset() throws IOException {
		getInputStream().reset();
	}
    
    @Override
    public boolean markSupported() {
		try {
			return getInputStream().markSupported();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
}
